<template>
    <div></div>
    <SearchNav />
    <div class="main" style="min-height: calc(100vh - 90px)">
        <div class="w">
            <!-- 品牌 -->
            <div class="options" v-show="showBand">
                <div>品牌</div>
                <div class="wrap">
                    <div class="text">
                        <ul>
                            <li
                                v-for="item in searchTipList.BrandList"
                                :key="item.id"
                                @click="brandChange(item.id, $event)"
                            >
                                {{ item.name }}
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            <el-divider style="margin: 0" />
            <!-- 分类 -->
            <div class="options" v-show="showCategory">
                <div>分类</div>
                <div class="wrap">
                    <div class="text">
                        <ul>
                            <li
                                v-for="item in searchTipList.CategoryList"
                                :key="item.id"
                                @click="categoryChange(item.id, $event)"
                            >
                                {{ item.name }}
                            </li>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- 商品卡片 -->
            <div class="product__block flex-row">
                <div class="product__none" v-if="proList.length === 0">暂无该商品</div>
                <div v-else v-for="(item, index) in proList" :key="index">
                    <div class="product__card" @click="proInfo(item.productid)">
                        <img :src="item.mainphoto" />
                        <div class="product__info">
                            <div class="name" :title="item.name">{{ item.name }}</div>
                            <div class="unit">规格: {{ item.specification }};</div>
                            <div class="view">品牌: {{ item.brandname }}</div>
                            <div>
                                <span class="price" v-if="item.salaprice == null" style="font-size: 18px">请询价</span>
                                <span class="price" v-else>￥{{ item.salaprice }}</span>
                                <el-button type="primary" class="el-button el-button--primary is-plain">
                                    加入购物车
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pagination-block">
                <el-config-provider :locale="zhCn">
                    <el-pagination
                        :current-page="Number(pageStatus.page)"
                        :page-size="Number(pageStatus.size)"
                        :page-sizes="[12, 24, 48]"
                        small="small"
                        background="background"
                        layout="prev, pager, next,sizes,total"
                        :total="Number(pageStatus.total)"
                        @size-change="sizeChange"
                        @current-change="pageChange"
                    />
                </el-config-provider>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import router from '@/router/index';
import SearchNav from '@/components/search-nav.vue';
import { searchStore } from '@/store/index.js';
import { searchTip } from '@/api/productApi.js';
import { useRoute } from 'vue-router';
import { ElConfigProvider } from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
const route = useRoute();
// 商品列表数据
let proList = ref([]);
// 是否显示分类
let showCategory = ref(true);
let showBand = ref(true);
// 搜索建议列表数据
let searchTipList = ref([]);
// ✨默认页面状态
let pageStatus = reactive({
    size: 12,
    page: 1,
    total: 1,
    brandids: [],
    categoryids: [],
    text: '',
});

/**
 * @description: 更改分页大小
 * @param {*} val
 * @return {*}
 */
const sizeChange = val => {
    pageStatus.size = val;
    searchData(pageStatus);
};
/**
 * @description: 更改搜索页数
 * @param {*} val
 * @return {*}
 */
const pageChange = val => {
    pageStatus.page = val;
    searchData(pageStatus);
    setTimeout(() => {
        window.scrollTo(0, 0);
    }, 200);
};

/**
 * @description: 更改品牌
 * @param {*} val
 * @return {*}
 */
const brandChange = (val, event) => {
    const eventDom = event.target;
    let array = pageStatus.brandids;
    const index = array.indexOf(val);
    if (index === -1) {
        // 如果数不在数组中，添加到数组
        array.push(val);
        eventDom.classList.add('active-style');
    } else {
        // 如果数在数组中，删除该数
        array.splice(index, 1);
        eventDom.classList.remove('active-style');
    }
    pageStatus.brandids = array;
    searchData(pageStatus);
};

/**
 * @description: 更改搜索分类
 * @param {*} val
 * @return {*}
 */
const categoryChange = (val, event) => {
    const eventDom = event.target;
    let array = pageStatus.categoryids;
    const index = array.indexOf(val);
    if (index === -1) {
        // 如果数不在数组中，添加到数组
        array.push(val);
        eventDom.classList.add('active-style');
    } else {
        // 如果数在数组中，删除该数
        array.splice(index, 1);
        eventDom.classList.remove('active-style');
    }
    pageStatus.categoryids = array;
    searchData(pageStatus);
};
/**
 * @description: 搜索商品方法
 * @param {*} data
 * @return {*}
 */

const searchData = data => {
    const loading = ElLoading.service({
        lock: true,
        text: '正在加载',
        background: 'rgb(255,255,255)',
    });

    let respon = searchStore.searchProduct(data);

    respon.then(res => {
        proList.value = res.result.data;
        pageStatus.total = res.result.total;
        loading.close();
    });
};

// 根据搜素关键词返回 分类 和 品牌
const seatchTipsInfo = async kw => {
    let tipList = await searchTip(kw);
    searchTipList.value = tipList.result;
};

// 商品详情跳转
const proInfo = proId => {
    let path = router.resolve({ path: '/product', query: { id: proId } });
    window.open(path.href, '_blank');
};

// 监听路由变化
watch(
    () => route.query,
    (newSearchData, oldSearchData) => {
        if (oldSearchData?.text !== newSearchData?.text && newSearchData?.text !== undefined) {
            console.log('模糊搜素');
            seatchTipsInfo(newSearchData.text);
            searchData(route.query);
        }
        if (newSearchData !== oldSearchData) {
            // 修改搜索参数
            if (route.query?.categoryids !== undefined) {
                const category = [parseInt(route.query.categoryids)];
                // 隐藏分类搜索栏
                showCategory.value = false;
                const temp = { ...route.query, categoryids: category };
                pageStatus = Object.assign({}, pageStatus, temp);
                searchData(pageStatus);
                seatchTipsInfo({ categoryids: category });
            }
            if (route.query?.brandids !== undefined) {
                const brand = [parseInt(route.query.brandids)];
                // 隐藏品牌搜索栏
                showBand.value = false;
                const temp = { ...route.query, brandids: brand };
                pageStatus = Object.assign({}, pageStatus, temp);
                searchData(pageStatus);
                seatchTipsInfo({ brandids: brand });
            }
            if (route.query?.text !== undefined) {
                searchData(pageStatus);
            }
        }
    },
    { immediate: true, deep: true }
);

// 页面挂载触发路由搜索
// onMounted(() => {
//     if (route.query.text !== undefined) {
//         pageStatus.text = route.query.text;
//     } else {
//         console.log(route.query)
//         // pageStatus = Object.assign(pageStatus, route.query);
//         // searchData(pageStatus);
//     }
// });
</script>

<style lang="scss">
.pagination-block {
    margin: 12px 0;
    height: 40px;
    // border: 1px solid red;
    background-color: #fff;
    overflow: hidden;
    .el-pagination {
        line-height: 40px;
        justify-content: center;
    }
}
.pagination-block + .pagination-block {
    margin-top: 10px;
}
.pagination-block .demonstration {
    margin-bottom: 16px;
}
.center {
    margin-top: 8px;
    justify-content: space-between;
}

.main {
    border-top: 1px solid #f9f9f9b1;
    background-color: #f1f3f5;
    overflow: hidden;
}
.active-style {
    color: #126abb;
}
.options {
    padding-bottom: 14px;
    // border: 1px solid red;
    display: flex;
    background-color: #fff;
    // margin-top: 12px;
    > div:first-child {
        width: 80px;
        padding: 0 10px;
        padding-top: 22px;
        text-align: center;
        font-weight: 700;
    }
}
.options:first-child {
    margin-top: 12px;
}

.wrap {
    display: flex;
    width: 1012px;
    // padding: 10px;
}

.text {
    overflow: hidden;
    text-align: justify;
    position: relative;
    > ul {
        padding-left: 0;
        margin-bottom: 0;
        li {
            height: 30px;
            line-height: 30px;
            cursor: pointer;
        }
    }
}

.text ul {
    display: flex;
    flex-wrap: wrap;
}
.text ul li {
    list-style-type: none;
    padding: 0 10px;
}
.product__block {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-column-gap: 12px;
}
.product__card {
    background-color: #fff;
    // width: 286px;
    width: 100%;
    height: 378px;
    border: 1px solid #eaeaea;
    margin-top: 12px;
    box-sizing: border-box;
    padding-top: 16px;
    transition: 0.6s;
    img {
        width: 192px;
        height: 192px;
        margin: 0 auto;
        display: block;
    }
    &:hover {
        box-shadow: #252f681a 0px 2px 10px 6px;
        transition: 0.6s;
        cursor: pointer;
    }
}
.product__info {
    margin: 24px auto 0 auto;
    width: 218px;
    > div {
        margin-top: 10px;
    }
    .name {
        font-size: 14px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .unit {
        color: #5a5a5a;
        font-size: 12px;
    }
    .view {
        color: #999;
        font-size: 12px;
    }
    .price {
        font-family: arial;
        font-weight: 600;
        color: #e1251b;
        font-size: 20px;
    }

    > div :last-of-type {
        position: relative;
    }
    .el-button {
        height: 24px;
        position: absolute;
        float: right;
    }
}
.product__none {
    margin: 0 auto;
    margin-top: 14px;
    font-size: 18px;
}
</style>
